<template>
  <view class="phone-login-area">
    <view class="btn-area text-center" v-if="isDebugMode">
      <!-- 调试用快捷登录按钮 -->
      <view class="debug-login-buttons">
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('grows')">
          刘大帅
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('factory')">
          工厂端管理员
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('kuguan')">
          库管员
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('caiwu')">
          财务人员
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('pinkong')">
          品控人员
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('pinkongjingli')">
          品控经理
        </wd-button>
        <wd-button class="debug-login-btn" size="mini" @click="setDebugUser('shengchanjingli')">
          生产经理
        </wd-button>
      </view>

      <view class="switch-login-way">
        <text class="switch-login-way-text" @click="$emit('switch-way', 0)">快捷登录</text>
        <text
          class="switch-login-way-text"
          @click="$emit('switch-way', 1)"
          style="margin-left: 20px"
        >
          用户注册
        </text>
      </view>
    </view>
    <view class="account-login-area">
      <view class="privacy-guide">
        <text class="guide-text">我们将通过短信验证码或微信授权获取您的手机号用于账户登录</text>
      </view>
      <view class="box account">
        <wd-icon name="mobile" size="15px"></wd-icon>
        <wd-text text="手机：" color="#000"></wd-text>
        <wd-input
          placeholder="请输入手机号"
          v-model="phoneNo"
          @change="handlePhoneChange"
        ></wd-input>
        <!-- 添加获取微信手机号按钮 -->
        <button
          class="custom-phone-button"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
          style="margin-left: 10px"
        >
          获取微信手机号
        </button>
      </view>
      <view class="box password">
        <wd-icon name="lock-on" size="15px"></wd-icon>
        <wd-text text="验证码：" color="#000"></wd-text>
        <wd-input placeholder="请输入验证码" v-model="smsCode"></wd-input>
        <wd-button
          :round="false"
          size="small"
          custom-class="sendSMSBtn"
          plain
          hairline
          :disabled="isSendSMSEnable"
          @click="handleSMSSend"
        >
          {{ getSendBtnText }}
        </wd-button>
      </view>
    </view>

    <view class="btn-area text-center">
      <wd-button custom-class="login align-top" :loading="loading" @click="handlePhoneLogin">
        {{ loading ? '登录...' : '登录' }}
      </wd-button>

      <view class="switch-login-way">
        <text class="switch-login-way-text" @click="$emit('switch-way', 0)">快捷登录</text>
        <text
          class="switch-login-way-text"
          @click="$emit('switch-way', 1)"
          style="margin-left: 20px"
        >
          用户注册
        </text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useToast } from 'wot-design-uni'
import { http } from '@/utils/http'
import { userApi } from '@/api/api'
import { useUserStore } from '@/store/user'

interface Props {
  loading?: boolean
}

interface Emits {
  (e: 'update:loading', value: boolean): void
  (e: 'switch-way', value: number): void
  (e: 'login-success'): void
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
})

const emit = defineEmits<Emits>()

const toast = useToast()
const userStore = useUserStore()

const phoneNo = ref('')
const smsCode = ref('')
const smsCountDown = ref(0)
const isDebugMode = ref(true)
let smsCountInterval: any = null

// 添加调试用户数据
const debugUsers = {
  factory: { phone: '13272408570', code: '123456' },
  kuguan: { phone: '13272408571', code: '123456' },
  caiwu: { phone: '13272408572', code: '123456' },
  pinkong: { phone: '13272408573', code: '123456' },
  pinkongjingli: { phone: '13272408574', code: '123456' },
  shengchanjingli: { phone: '13272408575', code: '123456' },
  grows: { phone: '13272408547', code: '123456' },
}

// 设置调试用户的方法
const setDebugUser = (userType: string) => {
  const user = debugUsers[userType as keyof typeof debugUsers]
  if (user) {
    phoneNo.value = user.phone
    smsCode.value = user.code
  }
}

const isSendSMSEnable = computed(() => {
  return smsCountDown.value > 0 || phoneNo.value.length < 4
})

const getSendBtnText = computed(() => {
  if (smsCountDown.value > 0) {
    return smsCountDown.value + '秒后发送'
  } else {
    return '发送验证码'
  }
})

const handlePhoneChange = () => {
  // 手机号变化时重置验证码
  smsCode.value = ''
}

// 添加获取微信手机号的方法
const getPhoneNumber = async (e: any) => {
  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      throw new Error('用户拒绝了授权')
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 将获取到的手机号填入表单
      phoneNo.value = res.result.phone as string
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif
    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信环境')
    phoneNo.value = '13272408547'
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '获取手机号失败')
  }
}

const handleSMSSend = () => {
  const smsParams = {
    mobile: phoneNo.value,
    smsmode: '0',
    type: 'loginFor',
  }

  const checkPhone = /^[1]([3-9])[0-9]{9}$/
  if (!smsParams.mobile || smsParams.mobile.length === 0) {
    toast.warning('请输入手机号')
    return false
  }
  if (!checkPhone.test(smsParams.mobile)) {
    toast.warning('请输入正确的手机号')
    return false
  }
  if (smsCountDown.value) {
    return
  }

  http.post(userApi.sendChangePhoneSms, smsParams).then((res: any) => {
    if (res.success) {
      smsCountDown.value = 60
      startSMSTimer()
    } else if (res.code === 500) {
      toast.warning(res.message)
    } else {
      smsCountDown.value = 0
      toast.warning(res.message)
    }
  })
}

const startSMSTimer = () => {
  smsCountInterval = setInterval(() => {
    smsCountDown.value--
    if (smsCountDown.value <= 0) {
      clearInterval(smsCountInterval)
    }
  }, 1000)
}

// 短信登录
const handlePhoneLogin = () => {
  const checkPhone = /^[1]([3-9])[0-9]{9}$/

  if (!phoneNo.value || phoneNo.value.length === 0) {
    toast.warning('请输入手机号')
    return
  }
  if (!checkPhone.test(phoneNo.value)) {
    toast.warning('请输入正确的手机号')
    return false
  }
  if (!smsCode.value || smsCode.value.length === 0) {
    toast.warning('请输入短信验证码')
    return
  }

  performLogin(phoneNo.value, smsCode.value)
}

// 执行登录操作
const performLogin = async (phoneNumber: string, captcha: string) => {
  emit('update:loading', true)

  const loginParams = {
    username: phoneNumber,
    captcha: captcha,
  }

  http
    .post(userApi.miniLogin, loginParams)
    .then((res: any) => {
      if (res.success) {
        const { result } = res
        const userInfo = result.userInfo
        userStore.setUserInfo({
          token: result.token,
          userid: userInfo.id,
          username: userInfo.username,
          realname: userInfo.realname,
          phone: userInfo.phone,
          avatar: userInfo.avatar,
          tenantId: userInfo.loginTenantId,
          localStorageTime: +new Date(),
          userRoleName: userInfo.userRoleName,
          userRole: userInfo.userRole,
          checkStatus: userInfo.checkStatus,
          permissionList: [],
        })
        if (userInfo.checkStatus === 0) {
          toast.warning('当前用户未解封，请联系管理员')
        }
        setPermission()

        emit('login-success')
      } else {
        toast.warning(res.message)
      }
    })
    .catch((err: any) => {
      const msg = err.message || '请求出现错误，请稍后再试'
      toast.warning(msg)
    })
    .finally(() => {
      emit('update:loading', false)
    })
}
const setPermission = async () => {
  const permissionList = await http.get(userApi.getUserPermissionsBytoken)
  userStore.setPermissionList(permissionList?.result?.codeList || [])
}
// 清理定时器
const clearTimer = () => {
  if (smsCountInterval) {
    clearInterval(smsCountInterval)
    smsCountInterval = null
  }
}

defineExpose({
  clearTimer,
})
</script>

<style lang="scss" scoped>
.phone-login-area {
  .privacy-guide {
    background-color: #f0f8ff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 20px;
    text-align: center;

    .guide-text {
      color: #666;
      font-size: 14px;
      line-height: 1.4;
    }
  }
  .account-login-area {
    .box {
      display: flex;
      align-items: center;
      min-height: 100upx;
      color: #000;
      border: 1px solid #eee;
      background-color: #fff;
      padding: 0 20upx;
      margin-bottom: 30upx;
      box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);

      :deep(.wd-text) {
        margin: 0 10upx;
      }

      :deep(.wd-input),
      :deep(.uni-input) {
        flex: 1;
        &::after {
          height: 0;
        }
      }

      .uni-input {
        text-align: left;
        font-size: var(--wot-input-fs, var(--wot-cell-title-fs, 14px));
        height: var(--wot-input-inner-height, 34px);
        color: var(--wot-input-color, #262626);

        .uni-input-placeholder {
          color: var(--wot-input-placeholder-color, #bfbfbf);
        }
      }
    }

    :deep(.sendSMSBtn) {
      margin-left: 20upx;
    }
  }

  .btn-area {
    :deep(.login) {
      margin-right: 30px;
      width: 100%;
      margin-right: 0;
      margin-bottom: 20px;
    }

    :deep(.wd-button) {
      --wot-button-medium-height: 41px;
      --wot-button-medium-fs: 16px;
      --wot-button-plain-bg-color: transparent;
      min-width: 100px;
      box-shadow: 3px 3px 4px rgba(0, 102, 204, 0.2);
    }
  }

  .switch-login-way {
    text-align: center;
    margin-top: 20px;

    .switch-login-way-text {
      color: #007aff;
      font-size: 14px;
    }
  }
}

/* 添加获取手机号按钮样式 */
.custom-phone-button {
  margin-left: 10px;
  background: transparent; /* 透明背景 */
  padding: 0 8px; /* 内边距 */
  height: 28px; /* 高度匹配 wd-button */
  line-height: 28px;
  font-size: 12px; /* 字体大小 */
  color: #333; /* 文字颜色 */
  border: 1px solid #ddd; /* 边框 */
  border-radius: 4px; /* 圆角 */
}

/* 如果需要 hover 效果 */
.custom-phone-button:hover {
  opacity: 0.8;
}
.debug-login-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 20px 0;

  .debug-login-btn {
    flex: 1;
    min-width: calc(50% - 5px);
  }
}
</style>
